package com.github.phoenics.newlives.common.interceptor;

import cn.hutool.json.JSONUtil;
import com.github.phoenics.newlives.common.base.RestResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 自动加入返回框架
 *
 * @author Phoenics Chow
 * on 2019年09月24日
 */
public class ResultResponse implements ResponseBodyAdvice<Object> {
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(body instanceof RestResponse ) {
            return body;
        }
        Object res= RestResponse.success(body);
        if(body instanceof String) {
            return JSONUtil.toJsonStr(res);
        }
        return res;
    }
}
